#!/usr/bin/python3
import logging

import rd

from urllib.parse import urlparse

__version__ = '0.1'

conn_timeout = 5
tls_verify = True

def get_host_meta(url, default_scheme=None):

    import requests

    args = {}
    if default_scheme:
        args['default_scheme'] = default_scheme

    (scheme, hostname, path) = rd.parse_uri_components(url, **args)

    """ Get host-meta data from .well-known """
    url = '{!s}://{!s}/.well-known/host-meta'.format(scheme, hostname)

    headers = {
        'Accept': ', '.join(rd.JRD_TYPES + rd.XRD_TYPES),
        'User-Agent': 'pywebdisco/{!s}'.format(__version__),
    }

    logging.debug('fetching RD from {!s}'.format(url))
    rsp = requests.get(url, headers=headers, timeout=conn_timeout, verify=tls_verify)

    if rsp.url != url:
        logging.info('Host-meta request redirected to {!s}'.format(rsp.url))

    content_type = rsp.headers.get('Content-Type', '').split(';', 1)[0].strip()
    logging.debug('RD content type is {!s}'.format(content_type))

    return rd.loads(rsp.content.decode(rsp.encoding if rsp.encoding else 'utf-8'), content_type)


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='Simple host-meta discovery')
    parser.add_argument('url', help='URL, possibly only hostname, of service we want discovery on')
    parser.add_argument('-d', '--debug', dest='debug', action='store_true', help='print debug logging output to console')
    parser.add_argument('-r', '--rel', metavar='REL', help='desired relation')
    parser.add_argument('-m', '--type', metavar='MIME', help='Content type, if rel can have multiple entries')
    parser.add_argument('-s', '--default-scheme', help='if no scheme is used in the url, use this')

    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)

    hm = get_host_meta(hostname, default_scheme=args.default_scheme)

    print('--- {!s}://{!s} ---'.format(scheme, hostname))

    if args.rel:
        link = wf.find_link(args.rel, mimetype=args.mimetype)

        if link is None:
            print('*** Link not found for rel={!s}'.format(args.rel))

        print('{!s}:\n\t{!s}'.format(args.rel, link))

    else:

        for rel in rd.KNOWN_RELS:
            link = getattr(hm, rel)
            if link:
                print('{}\t{}\t{}'.format(rel, link.href if link.href else link.template, link.type if link.type else '*'))
